from fastapi import Request, status,HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from jose import JWTError
from src.constants.resultcode import ResultCode
from src.utils.response import ApiResponse
from src.utils.logger import get_logger
from src.middlewares.jwt_middleware import JWTException

logger = get_logger("capcut")


async def validation_exception_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
    """参数校验错误处理器"""
    # 拼接完整错误信息
    error_messages = []
    for error in exc.errors():
        field = ".".join(str(loc) for loc in error["loc"])
        error_type = error["type"]
        error_msg = error["msg"]
        # print(error_msg)
        error_messages.append(f"{ResultCode.PARAM_VALIDATION_FAILED.message}{field} ({error_type}): {error_msg}")
        # error_messages.append(f"{ResultCode.PARAM_VALIDATION_FAILED.message}{error_msg}")
    
    full_message = "; ".join(error_messages)
    logger.error(f"全局参数验证错误: {full_message}",exc_info=True)
    return ApiResponse.error(
        result_code=ResultCode.PARAM_VALIDATION_FAILED,
        message=full_message
    )

async def jwt_exception_handler(request: Request, exc: JWTException) -> JSONResponse:
    """JWT异常处理器"""
    logger.warning(f"JWT认证异常: {exc.detail} - 路径: {request.url.path}")
    return ApiResponse.error(
        result_code=ResultCode.AUTHENTICATION_FAILED,
        message=exc.detail,
        status_code=exc.status_code
    )


async def jwt_error_handler(request: Request, exc: JWTError) -> JSONResponse:
    """JWT错误处理器"""
    logger.warning(f"JWT解析错误: {str(exc)} - 路径: {request.url.path}")
    return ApiResponse.error(
        result_code=ResultCode.AUTHENTICATION_FAILED,
        message="Token格式错误或已过期",
        status_code=status.HTTP_401_UNAUTHORIZED
    )

async def global_http_handler(request: Request, exc: HTTPException) -> JSONResponse:
    """HTTPException异常处理器"""
    logger.error(f"请求失败: {str(exc)}", exc_info=True)
    return ApiResponse.error(
        result_code=ResultCode.AUTHENTICATION_FAILED,
        message=str(exc),
        status_code=status.HTTP_401_UNAUTHORIZED
    )

async def global_exception_handler(request: Request, exc: Exception) -> JSONResponse:
    """全局异常处理器"""
    logger.error(f"全局系统异常捕获: {str(exc)}", exc_info=True)
    return ApiResponse.error(
        result_code=ResultCode.INTERNAL_SERVER_ERROR,
        message=str(exc),
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR
    )

def register_exception_handlers(app):
    """注册异常处理器"""
    app.add_exception_handler(RequestValidationError, validation_exception_handler)
    app.add_exception_handler(JWTException, jwt_exception_handler)
    app.add_exception_handler(JWTError, jwt_error_handler)
    app.add_exception_handler(Exception, global_exception_handler)
    app.add_exception_handler(HTTPException, global_http_handler)